package com.ky.server.dao;

import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import com.ky.common.entity.KyUser;
import com.ky.server.util.ConfigConstants;
import com.ky.server.util.PropertiesUtil;

public class UserDao {

	//将用于xml文件中的信息保存到map集合中
	private static HashMap<String , KyUser> userMap=new HashMap<>();
	private static Document document;
	private static String xmlPath=PropertiesUtil.getProperty(ConfigConstants.SERVER_USERS_PATH_KEY);
	
	static {
		SAXReader saxReader = new SAXReader();
		try {
			document = saxReader.read(xmlPath);
			//获取根元素
			Element rootElement = document.getRootElement();
			List<Element> elements = rootElement.elements("users");
			for (Element element : elements) {
				//获取user元素的子元素
				String userName = element.elementTextTrim("userName");
				String userPwd = element.elementTextTrim("userPwd");
				//将遍历的信息保存到map集合中
				userMap.put(userName, new KyUser(userName, userPwd));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//利用同步，添加用户并保存
	public synchronized static void addUser(KyUser kyUser) {
		Element rootElement = document.getRootElement();
		Element userElement = rootElement.addElement("user");
		userElement.addElement("userName").setText(kyUser.getUserName());
		userElement.addElement("userPwd").setText(kyUser.getUserPwd());
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("UTF-8");
		try {
			XMLWriter writer = new XMLWriter(new FileWriter(xmlPath), format);
			writer.write(document);
			writer.close();
			userMap.put(kyUser.getUserName(), kyUser);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	//根据用户名查找用户
	public static KyUser getUserByName(String userName) {
		
		return userMap.get(userName);
	}
	
}
